//
//  ViewController.m
//  WYMusic
//
//  Created by wy on 16/9/15.
//  Copyright © 2016年 wy. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "PlayViewCtl.h"

@interface ViewController ()<AVAudioPlayerDelegate>
@property(nonatomic,strong) NSString *playTime;
@property(nonatomic,strong) NSString *playDuration;
@property(nonatomic,assign) float currentPlayTime;

@property(nonatomic,assign)BOOL isPlay;
@end

@implementation ViewController
{
    AVPlayer *player;
    AVQueuePlayer *queuePlayer;
    NSMutableArray *playArr;
    id timeObserve;
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
    [self becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated
{
//     接触远程控制
//    
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    
    [self resignFirstResponder];
}

// 重写父类成为响应者方法
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    playArr =[NSMutableArray array];
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"dot_white"] forState:UIControlStateNormal];
    [self.progressSlider addTarget:self action:@selector(sliderValueChange:) forControlEvents:UIControlEventValueChanged];
    NSArray *songArr = @[@"http://m6.file.xiami.com/140/597628140/2100350707/1776162065_60307143_h.mp3?auth_key=76ffb6fa3360ab50054b22d3fe2685dc-1474070400-0-null",
                         @"http://m6.file.xiami.com/140/597628140/2100213122/1775388858_59439066_h.mp3?auth_key=690485d890edd7ba9a5ecc016a14a6c1-1474081200-0-null",
                         @"http://m6.file.xiami.com/172/32172/2100272650/1775605016_59685130_h.mp3?auth_key=f08970991c9215d961a010e9476410fe-1474081200-0-null"];
    for (NSString * obj in songArr) {
        AVPlayerItem *songItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:obj]];
        [playArr addObject:songItem];
    }
    player = [[AVPlayer alloc] initWithPlayerItem:playArr[0]];
    
    [self addObserver];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)playMusic:(UIButton *)sender {
    if (self.isPlay == YES) {
        [player play];
        [self.playBtn setImage:[UIImage imageNamed:@"player_pause"] forState:UIControlStateNormal];
    }else{
        [player pause];
        [self.playBtn setImage:[UIImage imageNamed:@"player_play"] forState:UIControlStateNormal];
    }
    self.isPlay = !self.isPlay;
}

- (IBAction)lastSong:(UIButton *)sender {
    self.loadTimeLabel.text =@"";
    [self removeObserver];
    [player.currentItem seekToTime:(kCMTimeZero) completionHandler:^(BOOL finished) {
        if ([playArr indexOfObject:player.currentItem] ==0) {
            [player replaceCurrentItemWithPlayerItem:playArr.lastObject];
        }else{
            [player replaceCurrentItemWithPlayerItem:playArr[[playArr  indexOfObject:player.currentItem]-1]];
        }
        [player play];
        [self addObserver];
    }];
}

- (IBAction)nextSong:(id)sender {
    self.loadTimeLabel.text =@"";
    [self removeObserver];
    [player.currentItem seekToTime:(kCMTimeZero) completionHandler:^(BOOL finished) {
        if ([playArr indexOfObject:player.currentItem]+1 == playArr.count) {
             [player replaceCurrentItemWithPlayerItem:playArr.firstObject];
        }else{
            [player replaceCurrentItemWithPlayerItem:playArr[[playArr  indexOfObject:player.currentItem]+1]];
        }
        [player play];
        [self addObserver];
    }];
    
}

-(void)addObserver{
    __weak typeof(self) weekSelf = self;
    __weak AVPlayer *weekPlayer = player;
    
    [player.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    [player.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    timeObserve = [player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        float current = CMTimeGetSeconds(time);
        float total = CMTimeGetSeconds(weekPlayer.currentItem.duration);
        weekSelf.currentPlayTime = current;
        if (total > 0) {
           weekSelf.progressSlider.maximumValue = total;
        }else{
           weekSelf.progressSlider.maximumValue = 300;
        };
        weekSelf.progressSlider.minimumValue = 0;
        weekSelf.progressSlider.value = current;
        
        if (current) {
            weekSelf.currentLabel.text =[weekSelf timetranstation:[NSString stringWithFormat:@"%.f",current]];
            weekSelf.totalLabel.text =[weekSelf timetranstation:[NSString stringWithFormat:@"%.f",total]];
            
            if (current == total) {
                [[NSNotificationCenter defaultCenter] addObserver:weekSelf selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:weekPlayer.currentItem];
            }
        }
    }];
}

- (void)playbackFinished:(NSNotification *)notice {
    //BASE_INFO_FUN(@"播放完成");
    [self nextSong:nil];
}

-(void)removeObserver{
    if (timeObserve) {
        self.progressSlider.value = 0;
        self.currentLabel.text =@"00:00";
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
        [player.currentItem removeObserver:self forKeyPath:@"status"];
        [player removeTimeObserver:timeObserve];
    }
}

-(NSString *)timetranstation:(NSString *)time{
    NSString *returnTime =[NSString string];
    NSInteger total = [time integerValue];
    if (total%60<10) {
        returnTime =[NSString stringWithFormat:@"0%ld:0%ld",total/60,total%60];
    }else{
         returnTime = [NSString stringWithFormat:@"0%ld:%ld",total/60,total%60];
    }
    return returnTime;
}


-(void)sliderValueChange:(UISlider *)slider{
    [player seekToTime:CMTimeMake(slider.value, 1.0)];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    AVPlayerItem * songItem = object;
    if ([keyPath isEqualToString:@"status"]) {
        switch (player.status) {
            case AVPlayerStatusUnknown:
              //  BASE_INFO_FUN(@"KVO：未知状态，此时不能播放");
                self.isPlay = NO;
                [self playMusic:self.playBtn];
                break;
            case AVPlayerStatusReadyToPlay:
               // self.status = SUPlayStatusReadyToPlay;
              //  BASE_INFO_FUN(@"KVO：准备完毕，可以播放");
                self.isPlay = YES;
                [self playMusic:self.playBtn];
                break;
            case AVPlayerStatusFailed:
              //  BASE_INFO_FUN(@"KVO：加载失败，网络或者服务器出现问题");
                 self.isPlay = NO;
                [self playMusic:self.playBtn];
                break;
            default:
                break;
        }
    }else  if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSArray * array = songItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue]; //本次缓冲的时间范围
        NSTimeInterval totalBuffer = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration); //缓冲总长度
        float total = CMTimeGetSeconds(songItem.duration);
        NSLog(@"共缓冲%.0f％",totalBuffer/total*100);
        self.loadTimeLabel.text =[NSString stringWithFormat:@"正在缓冲%.0f％",totalBuffer/total*100];
        if ([[NSString stringWithFormat:@"%.0f",totalBuffer/total*100] isEqualToString:@"100"]) {
            self.loadTimeLabel.text =@"";
        }else{
            self.loadTimeLabel.text =[NSString stringWithFormat:@"正在缓冲%.0f％",totalBuffer/total*100];
        }
        
        CGFloat currentPlayTime =  self.currentPlayTime;
        
        if (totalBuffer > currentPlayTime +5) {
            self.isPlay = YES;
            [self playMusic:self.playBtn];
        }else{
            self.isPlay = NO;
            [self playMusic:self.playBtn];
        }
    }
}

- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
    
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        switch (receivedEvent.subtype) { // 得到事件类型
                
            case UIEventSubtypeRemoteControlTogglePlayPause: // 暂停 ios6
                 self.isPlay = NO;
                
                [self playMusic:self.playBtn]; // 调用你所在项目的暂停按钮的响应方法 下面的也是如此
                
                break;
                
            case UIEventSubtypeRemoteControlPreviousTrack:  // 上一首
                [self lastSong:nil];
                
                break;
                
            case UIEventSubtypeRemoteControlNextTrack: // 下一首
                
                [self nextSong:nil];
                
                break;
                
            case UIEventSubtypeRemoteControlPlay: //播放
                self.isPlay = YES;
                [self playMusic:self.playBtn];
                
                break;
                
            case UIEventSubtypeRemoteControlPause: // 暂停 ios7
                
                self.isPlay = NO;
                [self playMusic:self.playBtn];
                 
                break;
                
            default:
                
                break;
                
        }
        
    }
    
}


- (IBAction)return:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
